package top.maof.mfcoin.block;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ByteUtil;
import lombok.Data;

import java.math.BigInteger;
import java.util.Base64;

/**
 * 区块头
 */
@Data
public class BlockHeader {
    // 上个区块hash
    private String previousHash;

    // 区块链版本号
    private int version;

    // 区块高度
    private long index;

    // 时间戳
    private long timestamp;

    // MerkleTree根hash值
    private byte[] hashMerkleTree;

    // 保存数据
    private byte[] data;

    // 随机数,挖矿工作量证明
    private long nonce;


    // 当前区块hash
    private String hash;

    // 挖矿阈值
    private BigInteger target;


    public static String hashBlock(BlockHeader blockHeader) {
        byte[] blockBytes = Base64.getDecoder().decode(blockHeader.previousHash);
        blockBytes = ArrayUtil.addAll(blockBytes, ByteUtil.intToBytes(blockHeader.version),
                ByteUtil.longToBytes(blockHeader.index), ByteUtil.longToBytes(blockHeader.timestamp),
                blockHeader.hashMerkleTree, blockHeader.data, ByteUtil.longToBytes(blockHeader.nonce));

        return Base64.getEncoder().encodeToString(blockBytes);
    }
}
